package com.example.restatr.Atcivity.Park;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.graphics.Paint;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Park.Bean.ParkScoreCommodityBean;
import com.example.restatr.Atcivity.Park.Bean.ParkScoreTopBean;
import com.example.restatr.Atcivity.Park.Bean.ParkScoreRecordBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ScoreTopAt extends AppCompatActivity {
    private Toolbar tb;
    private TextView barTitle;
    private EditText search;
    private TextView myRanking;
    private ImageView scoreLevel;
    private ListView scoreList;
    private List<ParkScoreTopBean.RowsBean> ScoreTopBeans = new ArrayList<>();
    private TextView score;
    private AlertDialog alertDialog;
    private LinearLayout dialog_scoreLevel;
    private ListView dialog_scoreRecord;
    private GridView dialog_scoreCommodity;
    private List<ParkScoreRecordBean.RowsBean> scoreRecordBeans = new ArrayList<>();
    private List<ParkScoreCommodityBean.RowsBean> scoreCommodityBeans = new ArrayList<>();
    private RelativeLayout shade;
    private LinearLayout progressLL;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_top_at);
        tb = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        myRanking = findViewById(R.id.myRanking);
        scoreLevel = findViewById(R.id.scoreLevel);
        scoreList = findViewById(R.id.scoreList);
        score = findViewById(R.id.score);
        shade = findViewById(R.id.shade);
        progressLL = findViewById(R.id.progress_LL);
        text = findViewById(R.id.text);
        Tools.SetBarTitle(tb, barTitle, "积分榜", search, this,true);
        tb.getMenu().removeItem(R.id.item1);
        tb.getMenu().getItem(0).setTitle("积分商城");
        tb.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                dialog_scoreLevel.setVisibility(View.GONE);
                dialog_scoreRecord.setVisibility(View.GONE);
                dialog_scoreCommodity.setVisibility(View.VISIBLE);
                selectCommodity();
                alertDialog.show();
                return true;
            }
        });
        GetScoreTop();
        CreateDialog();
    }

    //设置积分等级
    private void SetScoreLevel(int score, ImageView scoreLevel) {
        if (score >= 5000) {
            scoreLevel.setImageResource(R.drawable.ic_diamond);
        } else if (score >= 2000 && score < 5000) {
            scoreLevel.setImageResource(R.drawable.ic_platina);
        } else {
            scoreLevel.setImageResource(R.drawable.ic_gold);
        }

    }
    //创建dialog布局
    private void CreateDialog() {
        View inflate = getLayoutInflater().inflate(R.layout.score_level_dialog, null);
        dialog_scoreLevel = inflate.findViewById(R.id.scoreLevel);
        dialog_scoreCommodity = inflate.findViewById(R.id.scoreCommodity);
        dialog_scoreRecord = inflate.findViewById(R.id.scoreRecord);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        alertDialog = builder.setView(inflate).create();
    }
    //获取积分排行榜
    private void GetScoreTop() {
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/park/score/top/list", MainActivity.sp.getString("token", ""));
            ParkScoreTopBean parkScoreTopBean = new Gson().fromJson(token, ParkScoreTopBean.class);
            ScoreTopBeans.clear();
            ScoreTopBeans.addAll(parkScoreTopBean.getRows());
            runOnUiThread(() -> {
                if (ScoreTopBeans.size()>0){
                    shade.setVisibility(View.GONE);
                    scoreList.setAdapter(new ScoreTopListAdapter());
                    //我的排名下标
                    AtomicInteger pos = new AtomicInteger(0);
                    //筛选符合当前用户ID的集合
                    ParkScoreTopBean.RowsBean MyRowsBean = ScoreTopBeans.stream().filter(r -> {
                        pos.getAndIncrement();
                        return r.getUserId() == MainActivity.sp.getInt("userId", 0);
                    }).findAny().orElse(null);
                    myRanking.setText("我的排名：" + pos);
                    SetScoreLevel(MyRowsBean.getScore(), scoreLevel);
                    score.setText(MyRowsBean.getScore() + "分");
                    myRanking.setOnClickListener(v -> scoreList.setSelection(pos.get()));
                }
            });
        }).start();
    }
    //查询积分变更记录
    private void selectScoreAlterRecord() {
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/park/score/list", MainActivity.sp.getString("token", ""));
            scoreRecordBeans.clear();
            scoreRecordBeans.addAll(new Gson().fromJson(token, ParkScoreRecordBean.class).getRows());
            runOnUiThread(() -> {
                if (scoreRecordBeans.size()>0){
                    dialog_scoreRecord.setAdapter(new ScoreRecordAdapter());
                }
            });
        }).start();
    }
    //查询换购商品列表
    private void selectCommodity() {
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/park/product/list", MainActivity.sp.getString("token", ""));
            scoreCommodityBeans.clear();
            scoreCommodityBeans.addAll(new Gson().fromJson(token, ParkScoreCommodityBean.class).getRows());
            runOnUiThread(() -> {
                if (scoreCommodityBeans.size()>0){
                    dialog_scoreCommodity.setAdapter(new ScoreCommodityAdapter());
                }
            });
        }).start();
    }
    //积分兑换
    private void scoreExchange(String id){
        new Thread(()->{
            try {
                JSONObject jb = new JSONObject();
                String post = Tools.Post("/prod-api/api/park/score/consume/" + id, MainActivity.sp.getString("token", ""), jb.toString());
                JSONObject jx = new JSONObject(post);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(()->{
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();


    }
    //点击事件
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.score_LL:
                dialog_scoreRecord.setVisibility(View.VISIBLE);
                dialog_scoreLevel.setVisibility(View.GONE);
                dialog_scoreCommodity.setVisibility(View.GONE);
                selectScoreAlterRecord();
                alertDialog.show();
                dialog_scoreRecord.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        alertDialog.dismiss();
                    }
                });
                break;
        }

    }

    class ScoreTopListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return ScoreTopBeans.size();
        }

        @Override
        public Object getItem(int position) {
            return ScoreTopBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.score_top_list_item, null);
            ImageView avatar = convertView.findViewById(R.id.avatar);
            TextView userNick = convertView.findViewById(R.id.userNick);
            TextView Ranking = convertView.findViewById(R.id.Ranking);
            ImageView scoreLevel = convertView.findViewById(R.id.scoreLevel);
            TextView score = convertView.findViewById(R.id.score);
            LinearLayout scoreLL = convertView.findViewById(R.id.score_LL);

            Glide.with(ScoreTopAt.this)
                    .load(Tools.ip + "/prod-api" + ScoreTopBeans.get(position).getAvatar())
                    .transform(new CircleCrop())
                    .error(R.drawable.ic_baseline_account_circle_24)
                    .into(avatar);
            userNick.setText(ScoreTopBeans.get(position).getUserName());
            Ranking.setText("排名：" + (position + 1));
            score.setText(ScoreTopBeans.get(position).getScore() + "分");
            SetScoreLevel(ScoreTopBeans.get(position).getScore(), scoreLevel);
            scoreLL.setOnClickListener(v -> {
                dialog_scoreRecord.setVisibility(View.GONE);
                dialog_scoreCommodity.setVisibility(View.GONE);
                dialog_scoreLevel.setVisibility(View.VISIBLE);
                alertDialog.show();
            });
            return convertView;
        }
    }

    class ScoreRecordAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return scoreRecordBeans.size();
        }

        @Override
        public Object getItem(int position) {
            return scoreRecordBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.mileage_item_layout, null);
            TextView date = convertView.findViewById(R.id.date);
            TextView distance = convertView.findViewById(R.id.distance);
            TextView gasFilling = convertView.findViewById(R.id.gasFilling);
            TextView amount = convertView.findViewById(R.id.amount);

            date.setText(scoreRecordBeans.get(position).getChangeDate());
            distance.setText(scoreRecordBeans.get(position).getEvent() );
            gasFilling.setText(scoreRecordBeans.get(position).getType());
            amount.setText(scoreRecordBeans.get(position).getScore() + "分");
            return convertView;
        }
    }

    class ScoreCommodityAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return scoreCommodityBeans.size();
        }

        @Override
        public Object getItem(int position) {
            return scoreCommodityBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.score_commodity_item, null);
            TextView name =convertView.findViewById(R.id.name);
            TextView money =convertView.findViewById(R.id.money);
            TextView score =convertView.findViewById(R.id.score);
            TextView residue =convertView.findViewById(R.id.residue);
            MaterialButton exchange =convertView.findViewById(R.id.exchange);
            name.setText(scoreCommodityBeans.get(position).getName());
            money.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            money.setText("价格："+scoreCommodityBeans.get(position).getPrice()+"¥");
            score.setText("积分："+scoreCommodityBeans.get(position).getScore()+"分");
            residue.setText("剩余："+(scoreCommodityBeans.get(position).getTotal()-scoreCommodityBeans.get(position).getSaleQuantity())+"件");
            exchange.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    scoreExchange(String.valueOf(scoreCommodityBeans.get(position).getId()));
                    alertDialog.dismiss();
                    GetScoreTop();
                }
            });
            return convertView;
        }
    }
}